package cn.javaxxw.springboot.dao;

import cn.javaxxw.springboot.entity.User;
import lombok.RequiredArgsConstructor;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;
/**
 * 功能描述: dao接口实现类
 * @author  TuYong
 * @date  2022/9/6 14:01
 */
@Repository
@RequiredArgsConstructor
public class UserDaoImpl implements UserDao{

    private final JdbcTemplate jdbcTemplate;

    @Override
    public int add(User user) {
        return jdbcTemplate.update("insert into user(name, age, email) values(?, ?, ?)",
                user.getName(),user.getAge(),user.getEmail());
    }

    @Override
    public int update(User user) {
        return jdbcTemplate.update("UPDATE user SET name = ? ,age = ?,email = ? WHERE id = ?",
                user.getName(),user.getAge(),user.getEmail(),user.getId());
    }

    @Override
    public int delete(int id) {
        return jdbcTemplate.update("DELETE from user where id = ?",id);
    }

    @Override
    public User findById(int id) {
        User user = jdbcTemplate.queryForObject("select * from user where id = ?", (rs, arg1) -> {
            User user1 = new User();
            user1.setId(rs.getInt("id"));
            user1.setName(rs.getString("name"));
            user1.setAge(rs.getInt("age"));
            user1.setEmail(rs.getString("email"));
            return user1;
        },id);
        return user;
    }

    @Override
    public List<User> getAll() {
        String sql = "select * from user";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class), new Object[]{});
    }
}
